package com.ccb.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.common.utils.PageUtils;
import com.ccb.common.utils.Query;
import com.ccb.product.dao.CategoryDao;
import com.ccb.product.entity.CategoryEntity;
import com.ccb.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getTree() {
        // 获取所有分类信息
        List<CategoryEntity> allCategory = baseMapper.selectList(null);
        List<CategoryEntity> menus = allCategory.stream().
                filter(all -> all.getParentCid() == 0). //一级分类：parent_cid==0
                        map((menu) -> {
                    menu.setChildren(getChildrens(menu, allCategory)); //递归找子分类
                    return menu;
                }).
                sorted((a1, a2) -> (a1.getSort() == null ? 0 : a1.getSort()) - (a2.getSort() == null ? 0 : a2.getSort())).
                collect(Collectors.toList());
        return menus;
    }

    //
    //递归查找出所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().
                // 二级菜单，ParentCid==CatId即为该分类的子分类
                        filter(menu -> menu.getParentCid() == root.getCatId()).
                map(menu -> {
                    //找到子菜单,拿到第三级菜单,把第三级菜单放到第二级菜单下
                    menu.setChildren(getChildrens(menu, all));    //继续对子分类找子分类
                    return menu;
                }).
                sorted((a1, a2) -> (a1.getSort() == null ? 0 : a1.getSort()) - (a2.getSort() == null ? 0 : a2.getSort())).
                collect(Collectors.toList());
        return children;
    }

}